import { routerRedux } from 'dva/router';
import { stringify } from 'qs';
import { accountLogin, queryCurrent } from '@/services/account';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { reloadAuthorized } from '@/utils/Authorized';

export default {
  nampspace: 'account',

  //保存数据
  state: {
    status: undefined,
    current: {},
  },

  //方法实现
  effects: {

    *login({ payload, callback }, { call, put }) {
      const response = yield call(accountLogin, payload);

      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });

      //登录成功
      if (response.ErrorMessage == '' || response.ErrorMessage == undefined) {
        //重置权限
        reloadAuthorized();
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params;

        debugger
        //重定向
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            redirect = null;
          }
        }
        
        yield put(routerRedux.replace(redirect || '/home'));

        //用户Session
        sessionStorage.setItem('user_id', response.Data.user.Id);
      }

      if (callback) callback(response);
    },

    *currentUser({ }, { call, put }) {
      const response = yield call(queryCurrent);

      yield put({
        type: 'getCurrent',
        payload: response,
      });
    },
  },

  //回调
  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload.Data.user[0].OrgParentName);
      return {
        ...state,
        ...payload,
      };
    },
    getCurrent(state, { payload }) {
      return {
        ...state,
        current: payload.Data.user,
      };
    },
  },
};
